package com.zzz.springsecuritystudy.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zzz.springsecuritystudy.entity.AuthenticationUserDetails;
import com.zzz.springsecuritystudy.entity.Role;
import com.zzz.springsecuritystudy.entity.User;
import com.zzz.springsecuritystudy.exception.BadRequestException;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.crypto.generators.BCrypt;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.lang.model.element.VariableElement;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * @author zhuzhizun
 * @date 2021/9/15
 */
@Slf4j
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {





    @SneakyThrows
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {




        // 获取用户信息  通过用户名去查
        String encode = new BCryptPasswordEncoder().encode("123456");
        ArrayList<Role> roles = new ArrayList<>();
        Role admin = new Role(1, "admin");
        Role common = new Role(2, "user");
        roles.add(admin);
        roles.add(common);
        User user = new User(1, "zzz", encode, roles, 1);

        // SpringSecurity会自动转换UsernameNotFoundException为BadCredentialsException
        if (user == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        if (user.getStatus() == 0){
            throw new BadRequestException("用户被禁用");
        }

        // User封装成AuthenticationUserDetails
        AuthenticationUserDetails authenticationUserDetails = new AuthenticationUserDetails(user);

        // 用户角色
        List<GrantedAuthority> authorities = new ArrayList<>();
        //用于添加用户的权限。只要把用户权限添加到authorities
        user.getRole()
                .forEach(r -> authorities.add(new SimpleGrantedAuthority("ROLE_"+r.getRoleName())));

        authenticationUserDetails.setAuthorities(authorities);

        return authenticationUserDetails;
    }

}
